import { Vec2 } from 'cc';
import { find, Sprite, SpriteFrame,tween,Tween,Game,game as gameCCD, _decorator, Component, Label, Node ,Vec3 } from 'cc'
import { App } from '../../../App';
import { EventConst } from '../../../common/Common';
import { loadCommonPreFab, showGameActionPoint, showGameMulitExit } from '../../../tools/PopuUp';
import UtilTool from '../../../tools/UtilTool';
import { EnergyBar } from '../EnergyBar';
import { GameBaseModel } from '../GameBaseModel';
import { ACTION_POINT_R, FOUR_BALL_BASE, SYSTEM_ADDRESS } from '../GameManage';
import { GameModel4 } from './GameModel4';
import { GameFourUser } from './GameFourUser';
import { MultiRule } from '../../../hall/multiplay/MultiRule';
const { ccclass, property } = _decorator;

// 游戏2D界面
@ccclass('GameLayer4')
export class GameLayer4 extends Component {
    @property(Node)
    bg_fight : Node = null

    @property(Label)
    timeLabel : Label = null

    @property(Node)
    speedupSpr : Node = null

    @property(SpriteFrame)
    ballSpr = []

    // 倒计时剩余时间
    private countdown = 0
    // 左边玩家地址
    public leftUserAddress = ""
    // 右边玩家地址
    public rightUserAddress = ""

    onLoad() {
    //     gameCCD.on(Game.EVENT_HIDE, function(){
    //         if (this.node==null) return
    //         if(!this.isBackGround){
    //             this.isBackGround = true;
    //             UtilTool.printLog("切换后台");
                
    //         }
    //     }.bind(this));
    //     gameCCD.on(Game.EVENT_SHOW, function(){
    //         if (this.node==null) return
    //         if(this.isBackGround){
    //             UtilTool.printLog("切换前台");    
    //             this.isBackGround = false;
    //             this.reqGameData()
    //         }
    //     }.bind(this));
    }

    start() {
        let gameView = App.Model.gameView as GameModel4
        gameView.setHoleSwitch(false)

        // 观战的处理
        let Btn_giveup = find("Btn_giveup",this.bg_fight)
        let Btn_quit = find("Btn_quit",this.bg_fight)
        let Btn_watching = find("Btn_watching",this.bg_fight)
        if (App.Model.gameManage.isWatchGame){
            Btn_giveup.active = false
            Btn_quit.active = true
            Btn_watching.active = true
        }
        else{
            Btn_giveup.active = true
            Btn_quit.active = false
            Btn_watching.active = false
        }

        this.setCurrentPlayer()
        this.setTimeAction(-1)
        this.UpdataScore({})
        this.setUIView([])

        this.setActionPoint(new Vec2(0,0))
        //更新作用点位置
        App.Event.on(EventConst.ACTION_BALL_POINT,(data)=>{
            this.setActionPoint(data)
        },this)
    }

    update(deltaTime: number) {
        
    }

    /**
     * 更新分数比
     */
    UpdataScore(scoreData) {
        let myScore=0, otherScore=0
        for (const key in scoreData) {
            if (Object.prototype.hasOwnProperty.call(scoreData, key)) {
                const data = scoreData[key];
                if (key==this.leftUserAddress) {
                    myScore = data
                }
                else{
                    otherScore = data
                }
            }
        }

        let scoreLabel = find("scoreLabel",this.bg_fight).getComponent(Label)
        scoreLabel.string = myScore + "/" +  otherScore
    }

    /**
     * 设置当前击打玩家动画
     */
    setCurrentPlayer(address = SYSTEM_ADDRESS) {
        let myNode = find("mtNode/Node1",this.bg_fight)
        let otherNode = find("otherNode/Node1",this.bg_fight)
        Tween.stopAllByTarget(myNode)
        Tween.stopAllByTarget(otherNode)

        if (address==this.leftUserAddress){
            let tweenScale = tween(myNode)
                .to(0.2, {scale: new Vec3(1.2, 1.2, 1)})
                .to(0.2, {scale: new Vec3(0.95, 0.95, 1)})
                .to(0.2, {scale: new Vec3(1.0, 1.0, 1.0)})
            tween(myNode).repeatForever(tweenScale).start()
        }
        else if (address==SYSTEM_ADDRESS){
        }
        else{
            let tweenScale = tween(otherNode)
                .to(0.2, {scale: new Vec3(1.2, 1.2, 1)})
                .to(0.2, {scale: new Vec3(0.95, 0.95, 1)})
                .to(0.2, {scale: new Vec3(1.0, 1.0, 1.0)})
            tween(otherNode).repeatForever(tweenScale).start()
        }
    }

    /* 设置UI界面 */
    setUIView(allUserObj:GameFourUser[]) {
        let myAddress = find("mtNode/Node1/address",this.bg_fight).getComponent(Label)
        let myBall = find("mtNode/ball",this.bg_fight).getComponent(Sprite)
        let otherAddress = find("otherNode/Node1/address",this.bg_fight).getComponent(Label)
        let otherBall = find("otherNode/ball",this.bg_fight).getComponent(Sprite)

        myAddress.node.active = allUserObj.length>0
        myBall.node.active = allUserObj.length>0
        otherAddress.node.active = allUserObj.length>0
        otherBall.node.active = allUserObj.length>0

        if (allUserObj.length>0) {
            for (let index = 0; index < allUserObj.length; index++) {
                let item = allUserObj[index];

                // 设置左边玩家的归属
                let inLeft = false
                if (App.Model.gameManage.isWatchGame) {
                    if (index==0) {
                        inLeft = true
                    }
                }else{
                    if (item.mine) {
                        inLeft = true
                    }
                }

                if (inLeft) {
                    this.leftUserAddress = item.userAddress
                    myAddress.string = UtilTool.formatNickOrAddress({"nickname":item.userNickname, "address":item.userAddress})
                    if (item.hitBall==FOUR_BALL_BASE) {
                        myBall.spriteFrame = this.ballSpr[0]
                    }
                    else{
                        myBall.spriteFrame = this.ballSpr[1]
                    }
                }
                else{
                    this.rightUserAddress = item.userAddress
                    otherAddress.string = UtilTool.formatNickOrAddress({"nickname":item.userNickname, "address":item.userAddress})
                    if (item.hitBall==FOUR_BALL_BASE) {
                        otherBall.spriteFrame = this.ballSpr[0]
                    }
                    else{
                        otherBall.spriteFrame = this.ballSpr[1]
                    }
                }
            }
        }


        // 头像
        let head1 = find("mtNode/Node1/head",this.bg_fight)
        let head2 = find("otherNode/Node1/head",this.bg_fight)
        this.updateHead(head1, App.Model.gameManage.gameStartData.headIdMap[this.leftUserAddress])
        this.updateHead(head2, App.Model.gameManage.gameStartData.headIdMap[this.rightUserAddress])
    }

    // 更新头像
    updateHead(headNode, headId) {
        let headDict = App.Scene.getHallRes("images/head")
        if (headDict["head_" + headId]) {
            headNode.getComponent(Sprite).spriteFrame = headDict["head_" + headId]
        }
    }

    /**
     * 展示决战时刻
     */
    showSpeedUp(show) {
        this.speedupSpr.active = show
    }

    /**
     * 设置倒计时动画
     * @param countdown 剩余倒计时时间 秒
     */
    setTimeAction(countdown=0) {
        if (this.timeLabel == null) {
            return
        }

        if (countdown==-1) {
            this.timeLabel.node.active = false
            return
        }
        this.timeLabel.node.active = true

        this.countdown = countdown
        UtilTool.timeCountdown3(this.timeLabel, countdown, (type,time=0)=>{
            if (type==1) {
                this.countdown = time

                if (this.countdown <=1) {
                    // 时间倒计时还剩1秒的时候不能请求击球
                    let gameView = App.Model.gameView as GameModel4
                    if (gameView) {
                        gameView.cueCtrl.isHitBall = false
                    }
                }
            }
            else if (type==2) {

            }
        }) 
    }

    /**
     * 停止倒计时
     */
    stopTimeSchedule() {
        Tween.stopAllByTarget(this.timeLabel.node)
        this.setCurrentPlayer()
    }

    // 重置进度条
    resetProgress() {
        find("energyBar",this.node).getComponent(EnergyBar).resetProgress()
    }

    /** 
     * 点击认输
      */
    clickGiveUp() {
        App.Audio.playOneShot("click")
        let gameView = App.Model.gameView as GameModel4
        showGameMulitExit(gameView.viewNode)
    }

    /** 
     * 退出观战
      */
    clickWatch() {
        App.Audio.playOneShot("click")
        let gameView = App.Model.gameView as GameModel4
        gameView.reqQuitWatchMsg()
    }

    protected onDestroy(): void {
        App.Event.off(EventConst.ACTION_BALL_POINT, this.setActionPoint, this)
    }

    /** 
     * 点击作用点
      */
    clickActionPoint() {
        if (App.Model.gameManage.isWatchGame) {
            // 观战模式不能点击设置作用点
            return
        }

        let gameView = App.Model.gameView as GameBaseModel
        showGameActionPoint(gameView.viewNode)
    }

    /** 
     * 设置作用点
      */
    setActionPoint(pos) {
        let ratio = 50 / ACTION_POINT_R
        let point = find("actionBall/redpoint",this.node)
        point.setPosition(pos.x * ratio, pos.y * ratio)

        if (pos.x == 0 && pos.y == 0) {
            App.Model.gameManage.ballActionDial = 0
            App.Model.gameManage.setActionPoint(pos)
            App.Event.emit(EventConst.GAME_HIT_ACTIONVIEW)
        }
    }

    // 显示规则
    async onBtnQuestion() {
        App.Audio.playOneShot("click")
        let node = await loadCommonPreFab("prefabs/hall/multiplay/multiRule", null)
        node.getComponent(MultiRule).setGameType(1)
    }

}

